package com.jack.blog.service.serviceImpl;

import com.jack.blog.dao.BlogMapper;
import com.jack.blog.dao.MessageMapper;
import com.jack.blog.dto.BlogDto;
import com.jack.blog.dto.MessageDto;
import com.jack.blog.entity.Blog;
import com.jack.blog.entity.Message;
import com.jack.blog.service.MessageService;
import com.jack.blog.utils.DateUtil;
import com.jack.blog.utils.MessageUtil;
import com.jack.blog.vo.BlogVo;
import com.jack.blog.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageDto messageDto;
    @Autowired
    private BlogDto blogDto;

    @Override
    public List<MessageVo> getMessagesByBid(int bid) {
        return messageDto.MessageToMessageVo(messageMapper.queryMessages(bid));
    }

    @Override
    public Map<BlogVo,List<MessageVo>> getMessagesByUid(int uid, boolean reply) {
        Map<BlogVo,List<MessageVo>> map=new HashMap<>();
        List<Blog> blogs = blogMapper.queryBlogsByUid(uid,0,Integer.MAX_VALUE);
        for (Blog blog:blogs) {
            BlogVo blogVo = blogDto.BlogToBlogVo(blog);
            List<Message> messages = messageMapper.queryMessagesByReply(blog.getId(), reply);
            map.put(blogVo,messageDto.MessageToMessageVo(messages));
        }
        return map;
    }
    @Override
    @Transactional
    public MessageVo addMessage(int blogId, MessageVo messageVo) {
        Message message = messageDto.MessageVoToMessage(messageVo);
        message.setBid(blogId);
        messageMapper.insertMessage(message);
        return messageDto.MessageToMessageVo(message);
    }

    @Override
    public void replyMessage(int mid, String content) throws Exception {
        Timestamp replyTime = DateUtil.getTimestamp();
        Message message = messageMapper.queryMessage(mid);
        MessageUtil.sendMail(content,message.getEmail(),replyTime);
        messageMapper.updateMessage(mid,true,replyTime);
    }

}
